package blockingqueue;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by User on 2017/12/21.
 */
public class App {


    ReentrantLock lock = new ReentrantLock();

    Condition cannotEmpty = lock.newCondition();

    Queue queue = new ArrayDeque();

    public static void main(String[] args) {
        App app = new App();

        new Thread(()->{
            for (;;) {
                app.queue.add(new Object());
                System.out.println("添加了一个产品");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                app.lock.lock();
                app.cannotEmpty.signal();
                app.lock.unlock();
            }
        }).start();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{

                try {
                    for (;;) app.consume();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }).start();
        }


    }

    private void consume() throws InterruptedException {

        lock.lock();
        try {
            System.out.println("进来一个消费者");
            while (queue.size() == 0) {
                cannotEmpty.await();
            }

            System.out.println("开始消费");
            Thread.sleep(1000);
            queue.poll();
            System.out.println("消费结束");

            if (queue.size() > 0) cannotEmpty.signal();

        } finally {
            lock.unlock();
        }


    }



}
